package io.renren.modules.backstage.service.impl;

import com.aliyun.oss.model.PartETag;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tencent.common.pojo.Result;
import io.renren.common.exception.StatusCode;
import io.renren.common.utils.OSSClientUtil;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;
import io.renren.modules.backstage.service.VideoService;
import io.renren.modules.backstage.entity.ChapterEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.modules.backstage.dao.VideoDao;
import io.renren.modules.backstage.entity.VideoEntity;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;


@Service("videoService")
public class VideoServiceImpl extends ServiceImpl<VideoDao, VideoEntity> implements VideoService {
    @Resource
    VideoDao videoDao;

    private String bucket_name = "video/";

    private String uploadId = "";

    private String objectName = "";

    private List<PartETag> partETagList;

    private List<HashMap<String, Object>> resultList = new ArrayList<>();

    private List<InputStream> StreamList = new ArrayList<>();

    String filePath = UUID.randomUUID().toString();

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<VideoEntity> page = this.page(
                new Query<VideoEntity>().getPage(params),
                new QueryWrapper<VideoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage1(Map<String, Object> params) {

        Long pageNum = Long.parseLong((String) params.get("page"));
        Long pageSize = Long.parseLong((String) params.get("limit"));
        Page<VideoEntity> page = new Page<>(pageNum,pageSize);
        QueryWrapper<VideoEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("cid",params.get("cid"));
        Page page1 = videoDao.selectPage(page, wrapper);
        return new PageUtils(page1);
    }


    @Override
    public Result register(String fileMd5, String fileName, String fileSize, String mimetype, String fileExt) {

        getFileFolderPath(fileMd5);
        resultList = new ArrayList<>();
        StreamList = new ArrayList<>();
        String filePath = getFilePath(fileMd5, fileExt);
        Boolean flag = OSSClientUtil.doesObjectExist(filePath);
        if(flag){
            return new Result(StatusCode.ERROR,"视频已存在",false);
        }
        return new Result(StatusCode.OK,"视频不存在",true);
    }

    @Override
    public Result checkchunk(String fileMd5, Integer chunk, Integer chunkSize) {
        String chunkPath = getChunkFileFolderPath(fileMd5);
        Boolean chunkExist = OSSClientUtil.doesObjectExist(chunkPath + chunk);
        if(chunkExist){
            return new Result(StatusCode.ERROR,"块已存在",false);
        }
        return new Result(StatusCode.OK,"块不存在",true);
    }

    @Override
    public Result uploadChunk(MultipartFile multipartFile, String fileMd5, Integer chunk) {
        String chunkPath = getChunkFileFolderPath(fileMd5);
        Boolean chunkExist = OSSClientUtil.doesObjectExist(chunkPath + chunk);
        if(chunkExist){
            return new Result(StatusCode.ERROR,"无需创建块",false);
        }
        try {
//            HashMap<String, Object> resultMap = OSSClientUtil.uploadObject2OSS(multipartFile, chunkPath + chunk, fileMd5);
//            resultList.add(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(StatusCode.OK,"成功创建块",true);
    }

    @Override
    public Result mergechunks(String fileMd5, String fileName, Long fileSize, String mimetype, String fileExt) {
        //合并所有分块
        String mergeFilePath = getFilePath(fileMd5, fileExt);
        if (OSSClientUtil.doesObjectExist(mergeFilePath)) {
            OSSClientUtil.deleteFile("1908ayunoss",mergeFilePath);
        }
        //创建一个新文件
        OSSClientUtil.createFolder("1908ayunoss",mergeFilePath);
        Collections.sort(resultList, new Comparator<HashMap<String, Object>>() {
            @Override
            public int compare(HashMap o1, HashMap o2) {
                String a = (String) o1.get("uploadId");
                String b = (String) o2.get("uploadId");
                // 升序
                //return a.compareTo(b);
                //return o1.getName().compareToIgnoreCase(o2.getName());
                // 降序
                return b.compareTo(a);
            }
        });
        for (HashMap<String, Object> resultMap : resultList) {
            uploadId = (String) resultMap.get("uploadId");
            objectName = (String) resultMap.get("uploadId:" + uploadId);
            String chunkFilePath = "https://1908ayunoss.oss-cn-beijing.aliyuncs.com/" + objectName;
            System.err.println(chunkFilePath+"111111111111");
            try {
                URL url = new URL(chunkFilePath);
                URLConnection conn = url.openConnection();
                InputStream is = conn.getInputStream();
                StreamList.add(is);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        OSSClientUtil.MergeFile(StreamList,mergeFilePath);
        return new Result(StatusCode.OK,"成功创建块",true);
    }

    @Override
    public Result uploadVideo(MultipartFile file) {
        String chunkPath = bucket_name + filePath.substring(0,1) + "/" + filePath.substring(1,2) + "/" + filePath + "/";
        try {
            HashMap<String, Object> resultMap = OSSClientUtil.uploadObject2OSS(file, chunkPath);
            resultList.add(resultMap);
            //mergeUploadChunks(file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(StatusCode.OK,"成功创建块",true);
    }
//删除视频根据章节ID
    @Override
    public void deleteByCid(Integer cid) {
        QueryWrapper<VideoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid",cid);
        videoDao.delete(queryWrapper);
    }

    //视屏上传数据库通过ID
    @Override
    public void setURL(Map<String, Object> params){
        VideoEntity videoEntity = new VideoEntity();
        videoEntity.setVideoAddress((String) params.get("videoAddress"));
        QueryWrapper<VideoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("vid",params.get("vid"));
        videoDao.update(videoEntity,queryWrapper);
    }

    @Override
    public VideoEntity updateByVideoId(Integer vid) {
        QueryWrapper<VideoEntity> videoEntityQueryWrapper = new QueryWrapper<>();
        videoEntityQueryWrapper.eq("vid",vid);
        VideoEntity videoEntity = videoDao.selectOne(videoEntityQueryWrapper);
        return videoEntity;
    }

    private String getChunkFileFolderPath(String fileMd5) {
        return getFileFolderPath(fileMd5) + "chunk/";
    }

    private String getFilePath(String fileMd5, String fileExt) {
        return getFileFolderPath(fileMd5) + fileMd5 + "." + fileExt;
    }

    private String getFileFolderPath(String fileMd5) {
        return bucket_name + fileMd5.substring(0,1) + "/" + fileMd5.substring(1,2) + "/" + fileMd5 + "/";
    }




}